package com.yds.longlinks

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.yds.longlinks.client.MinaClientConnectionManager
import com.yds.longlinks.client.MinaClientService
import com.yds.longlinks.client.MinaClientSessionManager
import com.yds.longlinks.databinding.ActivityLongLinksBinding
import com.yds.longlinks.server.MinaServer
import java.util.Objects


class LongLinksActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLongLinksBinding

    private val mReceiver: MinaClientBroadcastReceiver = MinaClientBroadcastReceiver()
    private var mMinaClientService: Intent? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = DataBindingUtil.setContentView(this, R.layout.activity_long_links);
        binding.setLifecycleOwner(this)

        initListener()
        registerBroadcast()
    }

    private fun initListener() {
        binding.mButtonStartService.setOnClickListener { v ->
            mMinaClientService = Intent(this, MinaClientService::class.java)
            startService(mMinaClientService)
        }

        binding.mButtonSend.setOnClickListener { v ->
            val content = Objects.requireNonNull(binding.mEditTextInput.text).toString()
            if (TextUtils.isEmpty(content)) {
                Toast.makeText(this, "请输入", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            MinaClientSessionManager.getInstance().writeToServer(content)
        }

        binding.mButtonHostStart.setOnClickListener { v ->
            MinaServer.start()
        }
    }

    /**
     * 注册广播
     */
    @SuppressLint("NewApi")
    private fun registerBroadcast() {
        val filter = IntentFilter(MinaClientConnectionManager.BROADCAST_ACTION)
        registerReceiver(mReceiver, filter, RECEIVER_EXPORTED)
    }

    /**
     * 取消注册广播
     */
    private fun unRegisterBroadcast() {
        unregisterReceiver(mReceiver)
    }

    /**
     * 自定义广播接收器
     */
    private inner class MinaClientBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            Log.i("YDSimon", "localIPAddress = ${intent.getStringExtra(MinaClientConnectionManager.MESSAGE)}")
            binding.mTextViewReceive.text = intent.getStringExtra(MinaClientConnectionManager.MESSAGE)
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        stopService(mMinaClientService)
        unRegisterBroadcast()
    }
}